package com.yjhb.android.sbz.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.Conf;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.dialog.BindAliDialog;
import com.yjhb.android.sbz.dialog.InputDialog;
import com.yjhb.android.sbz.dialog.TipsDialog;
import com.yjhb.android.sbz.entity.UserInfo;
import com.yjhb.android.sbz.manager.ResManager;
import com.yjhb.android.sbz.mvp.settinginfo.SettingInfoPresenter;
import com.yjhb.android.sbz.mvp.settinginfo.SettingInfoView;
import com.yjhb.android.sbz.tool.CommonDialogCollect;
import com.yjhb.android.sbz.tool.DialogTool;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.tool.LoadingDialogTool;
import com.yjhb.android.sbz.tool.Tool;
import com.yjhb.android.sbz.tool.wx.WxLogin;
import com.yjhb.android.sbz.v2.activity.V2BindAliPayActivity;
import com.yjhb.android.sbz.v2.dialog.AvatarTipsDialog;
import com.yjhb.android.sbz.v2.dialog.NicknameTipsDialog;
import com.jojo.android.zxlib.base.BaseDialog;
import com.jojo.android.zxlib.interfaces.Callback;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxDataTool;
import com.jojo.android.zxlib.tool.ZxSpanTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.view.CircleImageView;
import com.jojo.android.zxlib.view.dialog.ILoading;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * 创建者 zx
 * 创建时间 2020/11/19 14:41
 */
public class SettingInfoActivity extends BaseActivity<SettingInfoPresenter> implements SettingInfoView {
    private final String TAG = "SettingInfoActivity";
    private final int REQUEST_IMAGE = 8001; //图片选择
    private final int REQUEST_MODIFY_NC = 8002; //修改昵称
    private final int REQUEST_MODIFY_PHONE = 8003; //绑定手机号

    @BindView(R.id.head_iv)
    CircleImageView head_iv;
    @BindView(R.id.nickname_tv)
    TextView nickname_tv;
    @BindView(R.id.id_tv)
    TextView id_tv;
    @BindView(R.id.phone_tv)
    TextView phone_tv;
    @BindView(R.id.name_tv)
    TextView name_tv;
    @BindView(R.id.idCard_tv)
    TextView idCard_tv;
    @BindView(R.id.wx_bind_tv)
    TextView wx_bind_tv;
    @BindView(R.id.zfb_bind_tv)
    TextView zfb_bind_tv;
    @BindView(R.id.my_inviter_tv)
    TextView myInviterTv;
    @BindView(R.id.my_inviter)
    RelativeLayout myInviter;
    @BindView(R.id.rl_phone)
    RelativeLayout rlPhone;

    private ILoading loadingDialog;

    @Override
    protected SettingInfoPresenter initPresenter() {
        return new SettingInfoPresenter(this);
    }

    @Override
    protected boolean isImmerse() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting_info;
    }

    @Override
    protected void initUI() {
        loadingDialog = LoadingDialogTool.createDialog(this);
        loadingDialog.setTipsText("上传中...");
        updateUi();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void regEvent() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void onBack(View view) {
        finish();
    }

    @OnClick(R.id.head_layout)
    public void head_layout() {
        AvatarTipsDialog tipsDialog = new AvatarTipsDialog(this);
        tipsDialog.setOnClickListener(new BaseDialog.OnClickListener() {
            @Override
            public void onClick(Dialog dialog, int button) {
                dialog.dismiss();
                new RxPermissions(getActivity()).request(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                Tool.getPictureSelector(getActivity(), 1)
                                        .forResult(Conf.REQUEST_IMAGE);
                            }
                        });
            }
        });
        tipsDialog.show();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                // 获取返回的图片列表
                List<LocalMedia> path = (List<LocalMedia>) data.getSerializableExtra(PictureConfig.EXTRA_RESULT_SELECTION);
                loadingDialog.show();
                presenter.uploadFile(path.get(0).getPath());
            }
        }
        if (requestCode == REQUEST_MODIFY_NC) {
            if (resultCode == RESULT_OK) {
                presenter.updateNickName(data.getStringExtra("result"));
            }
        }

        if (requestCode == REQUEST_MODIFY_PHONE) {
            if (resultCode == RESULT_OK) {
                presenter.getUserInfo();
            }
        }
    }

    private void updateUi() {
        UserInfo userInfo = App.userInfo;
        if (userInfo != null) {
            Glide.with(this).load(userInfo.getAvatar())
                    .apply(new RequestOptions().placeholder(R.mipmap.test_head))
                    .into(head_iv);
            nickname_tv.setText(userInfo.getNickName());
            id_tv.setText(userInfo.getId());
            if (TextUtils.isEmpty(userInfo.getPhone())) {
                phone_tv.setText("未绑定");
            } else {
                phone_tv.setText(ZxDataTool.hideMobilePhone4(userInfo.getPhone()));
            }
            if (TextUtils.isEmpty(userInfo.getRealName())) {
                name_tv.setText("未实名");
            } else {
                name_tv.setText(ZxDataTool.hideNameSuffix(userInfo.getRealName()));
            }
            if (TextUtils.isEmpty(userInfo.getIdentityNum())) {
                idCard_tv.setText("未实名");
            } else {
                idCard_tv.setText(ZxDataTool.hideIdCardSuffix(userInfo.getIdentityNum()));
            }
            if (TextUtils.isEmpty(userInfo.getWxOpenId())) {
                wx_bind_tv.setText("未绑定");
            } else {
                wx_bind_tv.setText("已绑定");
            }
            if (TextUtils.isEmpty(userInfo.getZfbAccount())) {
                zfb_bind_tv.setText("未绑定");
            } else {
                zfb_bind_tv.setText("已绑定");
            }
            myInviter.setEnabled(true);
            myInviterTv.setTextColor(getResources().getColor(R.color.black_33));
            if (userInfo.getParentId() == null || userInfo.getParentId() == 0) {
                Date date = App.userInfo.getCreateTime();
                if (System.currentTimeMillis() - date.getTime() > 1000 * 60 * 60 * 24 * 7) {
                    myInviterTv.setText("已过期");
                    myInviter.setEnabled(false);
                } else {
                    myInviterTv.setTextColor(ResManager.getThemeColor());
                    myInviterTv.setText("未绑定");
                }
            } else {
                myInviterTv.setText(String.valueOf(userInfo.getParentId()));
            }
        }
    }


    /**
     * 实名认证弹窗
     */
    private void showVerified() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_verified, null, false);
        final EditText et_name = view.findViewById(R.id.et_name);
        final EditText et_idCard = view.findViewById(R.id.et_idCard);
        View btn_bind = view.findViewById(R.id.bind_tv);
        View close_iv = view.findViewById(R.id.close_iv);
        final Dialog dialog = DialogTool.createDialog(this, view);
        btn_bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Tool.isEditEmpty(et_name)) {
                    ZxToast.showBottomToastLight("请输入姓名");
                    return;
                }
                if (Tool.isEditEmpty(et_idCard)) {
                    ZxToast.showBottomToastLight("请输入身份证号");
                    return;
                }
                if (!ZxDataTool.isIdCard(et_idCard.getText().toString())) {
                    ZxToast.showBottomToastLight("身份证号有误，请检查身份账号是否输入正确");
                    return;
                }
                loadingDialog.show();
                presenter.updateIdentityInfo(et_name.getText().toString(), et_idCard.getText().toString());
                dialog.dismiss();
            }
        });
        close_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    /**
     * 绑定支付宝弹窗
     */
    private void showBindZfb() {
//        BindAliDialog aliDialog = new BindAliDialog(this);
//        aliDialog.show();
        ZxActivityTool.skipActivity(this, V2BindAliPayActivity.class);
    }


    @OnClick(R.id.nickname_tv)
    public void nickname_tv() {
        NicknameTipsDialog tipsDialog = new NicknameTipsDialog(this);
        tipsDialog.setOnClickListener(new BaseDialog.OnClickListener() {
            @Override
            public void onClick(Dialog dialog, int button) {
                dialog.dismiss();
                Intent intent = new Intent(SettingInfoActivity.this, ModifyActivity.class);
                intent.putExtra("target", "昵称");
                startActivityForResult(intent, REQUEST_MODIFY_NC);
            }
        });
        tipsDialog.show();
    }

    @OnClick(R.id.rl_phone)
    public void rl_phone() {
        if (TextUtils.isEmpty(App.userInfo.getPhone())) {
            Intent intent = new Intent(this, BindPhoneActivity.class);
            startActivityForResult(intent, REQUEST_MODIFY_PHONE);
        }
    }

    @OnClick({R.id.name_tv, R.id.idCard_tv})
    public void verified() {
        UserInfo userInfo = App.userInfo;
        if (TextUtils.isEmpty(userInfo.getIdentityNum())) {
            CommonDialogCollect.showVerified(this, new Callback<Map<String, String>>() {
                @Override
                public void callback(Map<String, String> stringStringMap) {
                    loadingDialog.show();
                    presenter.updateIdentityInfo(stringStringMap.get("name"), stringStringMap.get("idCard"));
                }
            });
        }
    }

    @OnClick({R.id.zfb_bind})
    public void zfb_bind_tv() {
        UserInfo userInfo = App.userInfo;
        if (TextUtils.isEmpty(userInfo.getZfbAccount())) {
            showBindZfb();
        } else {
            TipsDialog tipsDialog = new TipsDialog(this);
            tipsDialog.setTitle("信息");
            String zfb = "支付宝账号:" + userInfo.getZfbAccount();
            String change = "更改";
            String name = "姓名:" + userInfo.getZfbName();
            String ID = userInfo.getIdentityNum();
            if (!TextUtils.isEmpty(ID) && ID.length() == 18) {
                ID = ID.substring(0, 14) + "****";
            }
            String idCard = "身份证号:" + ID;
            CharSequence content = name + "\n" + idCard + "\n" + zfb + "  " + change;
            int index = content.toString().indexOf(change);
            content = ZxSpanTool.ColorSpan(content, index, index + change.length(),
                    Color.parseColor("#1d7ddd"));
            content = ZxSpanTool.ClickSpan(content, index, index + change.length(),
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            tipsDialog.dismiss();
                            change();
                        }
                    });
            tipsDialog.setContent(content);
            tipsDialog.getContentTextView().setMovementMethod(LinkMovementMethod.getInstance());
            tipsDialog.setButtonVisibility(TipsDialog.TYPE_CANCEL, View.GONE);
            tipsDialog.setOnClickListener(new TipsDialog.OnClickListener() {
                @Override
                public void onClick(int type) {
                    tipsDialog.dismiss();
                }
            });
            tipsDialog.setSubmitText("确定");
            tipsDialog.show();
        }
    }

    private boolean verifyZfb(String text) {
        //如果符合手机号正则，则验证通过
        if (ZxDataTool.isMobile(text)) {
            return true;
        }
        //如果有@符号，则验证通过
        if (text.contains("@")) {
            return true;
        }
        return false;
    }


    void change() {
        InputDialog inputDialog = new InputDialog(this);
        inputDialog.setTitleText("更换支付宝账号");
        inputDialog.getInputView().setInputType(InputType.TYPE_CLASS_TEXT);
        inputDialog.setTipsText("只能更改支付宝账号，不能更改姓名，支付宝账号必须属于该姓名，每年最多更改3次。" +
                "\n已绑定的姓名：" + App.userInfo.getZfbName());
        inputDialog.setOnClickListener(new InputDialog.OnClickListener() {
            @Override
            public void onClick(int button) {
                if (button == InputDialog.BUTTON_SUBMIT) {
                    if (TextUtils.isEmpty(Tool.getText(inputDialog.getInputView()))) {
                        ZxToast.showINFOBottomToast("请先填写新的支付宝账号");
                        return;
                    }
                    if (!verifyZfb(Tool.getText(inputDialog.getInputView()))){
                        ZxToast.showINFOBottomToast("请填写正确的支付宝账号");
                        return;
                    }
                    presenter.changeZfb(Tool.getText(inputDialog.getInputView()));
                }
                inputDialog.dismiss();
            }
        });
        inputDialog.getInputView().setHint("请输入新的支付宝账号");
        inputDialog.show();
    }

    @OnClick({R.id.wx_bind_tv})
    public void wx_bind_tv() {
        if (TextUtils.isEmpty(App.userInfo.getWxOpenId())) {
            WxLogin.login();
        }
    }

    @OnClick(R.id.my_inviter)
    void my_inviter() {
        ZxActivityTool.skipActivity(this, MyInviterActivity.class);
    }

    @Override
    public void onOk() {
        //更新信息后重新拉取用户信息
        presenter.getUserInfo();
        loadingDialog.cancel();
        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
    }


    /*
        接收全局消息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(EventMsg eventMsg) {
        if (eventMsg.msg == EventMsg.USER_WX_RESULT) {
            SendAuth.Resp resp = (SendAuth.Resp) eventMsg.object;
            if (resp != null && resp.errCode == BaseResp.ErrCode.ERR_OK) {
                presenter.bindWx(resp.code);
            }
        } else if (eventMsg.msg == EventMsg.USER_UPDATE_OK) {
            updateUi();
        }
    }

    @Override
    public void onUserInfo(UserInfo userInfo) {
        if (userInfo != null)
            App.updateUserInfo(userInfo);
        updateUi();
    }

    @Override
    public void onFailure(int code, String msg) {
        ZxToast.showCenterToastLight(msg);
        loadingDialog.cancel();
    }


    @Override
    public void onWait(String tips) {
        loadingDialog.setTipsText(tips);
        loadingDialog.show();
    }

    @Override
    public void onZfbChangeSuccess() {
        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
        loadingDialog.cancel();
        ZxToast.showSuccessBottomToast("支付宝账号更改成功！");
    }
}
